/* qDatePicker.js (qJSLib)
 
    @Summary    : qDatePicker Widget
    @Author     : Timothy C. Quinn
    @License    : http://www.opensource.org/licenses/mit-license.php
  
    @Dependencies:
     - qCore.js (qJSLib)
     - qBase.js (qJSLib)
     - qHtml.js (qJSLib)
     - jquery.js
   
    @Notes:
     - (none)
   
    @Todo:
     - 
*/


qDPWidget_StaticMembers = {/* qCal Static Members */
    constants: {/* No not name const or it will kill IE :( */
         // (none)
         SDF_defDate: "MMM d, yyyy"
        ,SDF_defDateTime: "MMM d, yyyy h:mm a"
        ,SDF_defDateTimeSec: "MMM d, yyyy h:mm:ss a"
    }
    ,other: {
         instances: []
        ,pickerCtr: 0
        ,create: function qcal_st_create(oDiv, jOpt){
            var t=this,oSW;
            oSW = new qSelectWidget(oDiv, jOpt);
            return oSW;
        }
        ,register: function qcal_st_register(jOpt){
            var
                t=_qclient,h=qHtml
               ,f,oTarget,spDP,oTP,elTF,elTB
               ,oDivDP,bNewDP=false,iCPNo=(++qDPWidget.pickerCtr)
            ;
            elTB=agetParam_elem("jOpt", jOpt, "elemVal", true);
            elTF=agetParam_elem("jOpt", jOpt, "elemText", false);

            oTarget=(isDef(elTF)?elTF:elTB);
//pc(
//     "\n elTB = "+elTB
//    +"\n elTF = "+elTF
//    +"\n isDef elTF = "+isDef(elTF)
//    +"\n oTarget = "+oTarget
//    +"\n iCPNo = "+iCPNo
////    +"\n ccc:\n"+s$.pad(q$.dump(ddd))
//);
            oTarget.style.marginRight="2px";
            oTP=oTarget.parentNode;

          // Create Floating Element
            if( !(oDivDP = getElem("divDP")) ){
                $( oDivDP = _d.createElement("div") ).attr({id: "divDP"});
                _d.body.appendChild(oDivDP);
                qFloatElem.define(oDivDP);
                _w._qcal= new qDPWidget(oDivDP);// <~ may cause memory leak issue?
            };

          // Create DP Button
            $(spDP = _d.createElement("span"))
                .attr({id: "dpImg_"+iCPNo})
                .css({verticalAlign: "middle"})
                .html("<img src='"+imagePath+"CalButton.gif' style='border: 0px;'>")
                .bind("click", function spDP_click(e){
                    var t=_qclient,oS=this,oFlt,widg;

                    oFlt=oDivDP;
                    widg=oFlt.getWidget();
                    
                    if(oFlt.isOpen()){
                    	oFlt.close()
                    	if(widg.curPicker==oS)return
                    }
                    
                    widg.curPicker=oS;

//pc(
//     "\n oFlt = "+oFlt
//    +"\n oFlt.isOpen = "+oFlt.isOpen()
//    +"\n visibility = "+oFlt.style.visibility
//    +"\n widg = "+widg
//);
//                    if(oFlt.isOpen()){
//                        oFlt.close();
//                    }else{
                        oFlt.open({parent: oS, position: qHtml.POS_BL, ofsX: 7, ofsY: -3});
//                    };
                });

            spDP.jOpt=jOpt;
            spDP.elemVal=elTB;
            spDP.elemText=elTF;


            if(jOpt.bindTBEvents){
            	$(elTB)
            		.bind("keydown", function dateTB_onkeydown(e){//e=getEvent(e);
						var oTB=this;
						if(e.keyCode!=13)return;
//pc(
//     "\n e = "+e
//    +"\n e.keyCode = "+e.keyCode
//    +"\n oTB = "+oTB
//);
						oTB.blur(e);
					})
					.bind("blur", function dateTB_onblur(e,oTB){//e=getEvent(e);
						var d,s;
						oTB=oTB?oTB:this
						s=oTB.value.trim()
						try{
//pc(
//     "\n e = "+e
//    +"\n oTB = "+oTB
//    +"\n s = "+s
//);
							if(s.indexOf("(invalid")==0)return;
							if(s==="")return
							d = new QDate(s);
							if(d.isValid){
								oTB.value=d.format(
									!jOpt.showTime?	qDPWidget.SDF_defDate
									:jOpt.showSecs?	qDPWidget.SDF_defDateTimeSec
									:				qDPWidget.SDF_defDateTime
								);
							} else {
								/* todo - make hover with warning (alerts bite ;) */
							};
						}catch(x){debugErr(x)}
					})
//				assignEventListener(elTB,"keydown", qDPWidget.dateTB_onkeydown);
//				assignEventListener(elTB,"blur", qDPWidget.dateTB_onblur);
				
            };

            oTP.appendChild(spDP);

        }
//        ,dateTB_onkeydown: function dateTB_onkeydown(e){e=getEvent(e);
//			var o=e.target;
//			if(e.keyCode!=13)return;
//pc(
//     "\n e = "+e
//    +"\n e.keyCode = "+e.keyCode
//    +"\n o = "+o
//);
//			qDPWidget.dateTB_onblur(e);
//		}
//        ,dateTB_onblur: function dateTB_onblur(e){e=getEvent(e);
//			var o=e.target,d,s=o.value;
//pc(
//     "\n e = "+e
//    +"\n o = "+o
//);
//			if(s.indexOf("(invalid")==0)return;
//			d = new QDate(s);
//			if(d.isValid){
//				o.value=d.format("MMM d, yyyy h:mm a");
//			} else {
//				o.value="(invalid date - "+s+")";
//			};
//		}
    }
};
qDPWidget=QWidget.extend({
    className :"qDPWidget"
  // Constructor
    ,base_constr :function Cal_base_constr(oDiv){
//      pc(">>")
        var t=this,aInst=qDPWidget.instances,v;
        try {
            qObjAppend(t,qDPWidget_StaticMembers.constants);
            t.priv_no=aInst.length;aInst.p(t);
            t.base({instance:t,name:"qcal_"+t.priv_no});

            if(!isElem(oDiv))qErr("oDiv is not an HTML Element!");

            t.ctnr=oDiv;
            oDiv.getWidget = function cal_getWidget(){return t};
            t.init();

        }catch(exc){qErr(t.className+" Base Constructor Failed: ",exc)}
//      pc("<<")
    }

   ,showTime: false
   ,showSecs: false
   ,minPrec: 0
   ,timeSet: false
   ,valElem: null
   ,dispElem: null
   ,curPicker: null

   ,CAL_IMG: {tag: "img", _style: "cursor: hand; cursor: pointer;   opacity: 0.5; filter: alpha(opacity=50)"}
   ,isOpening: function Cal_isOpening(){//pc("called")
        var t=this,oPicker=t.curPicker,elTB=oPicker.elemVal,jOpt=oPicker.jOpt;

      // Capture Settings
        t.showTime = jOpt.showTime;
        t.showSecs = jOpt.showSecs;
        t.minPrec = agetParam_int("jOpt", jOpt, "minPrec", false);
        t.timeSet=false;

//pc(
//     "\n t = "+t
//    +"\n oPicker = "+oPicker
//    +"\n elTB = "+elTB
//    +"\n t.showTime = "+t.showTime
//    +"\n t.showSecs = "+t.showSecs
//    +"\n t.minPrec = "+t.minPrec
//);
      // Load Value
        if((d=new QDate(elTB.value)).isValid){
            t.sLoadDate = d.format(t.SDF_defDate);
            t.iHour=d.getHour24();
            t.iMinute=d.getMinute();
            t.iSecond=d.getSecond();
//pc(
//     "\n Date Parsed OK"
//    +"\n Raw Date= "+elTB.value
//    +"\n t.sLoadDate = "+t.sLoadDate
//    +"\n t.iHour = "+t.iHour
//    +"\n t.iMinute = "+t.iMinute
//    +"\n t.iSecond = "+t.iSecond
//);
        } else {
//pc(
//     "\n Date Not Parsed!"
//    +"\n Raw Date= "+elTB.value
//);
            d=new QDate();
            t.iHour=12;
            t.iMinute=0;
            t.iSecond=0;
        };
//pc(
//     "\n d = "+d
//);

        t.sCurDate=(new QDate()).format(t.SDF_defDate);
        t.iMonth=parseInt(d.format("M"));
        t.iYear=parseInt(d.format("yyyy"));

        if(t.showTime){
          // Update Minutes
        	dd = agetElem("tdMinute").getWidget();
        	dd.clearAll();
			for(var i=0;i<60;i++){
			    if( t.minPrec==0 || (i%t.minPrec)==0 )
			    	dd.addOption(new qSWOption((i>9?i:"0"+i), i), true)
			}
			dd.rebuild();
		};

        agetElem("divTimeBlock").style.display=(t.showTime?"":"none");

      // Finish
        t.updateCal();
    }
   ,isClosing: function Cal_isClosing(){//pc("called");
        var t=this;
    }
   ,init: function Cal_init(){
        var
             t=this,h=qHtml
            ,d,oM,o,sMsg=""
            ,s="", opt,qSW
        ;
        try {
            s+=
                "<div id='divCalMain' align=center style='-moz-user-select: none; border: 1px solid #26518D; background-color: #DDDDDD; width: "+(is.ie?9:9)+"em'>"
                +    "<div align=center style='padding: 1px;'>"
                +         h.tblHd({_width: "100%"})
                +            "<tr style='font-size: 80%'>"
                +               h.tblCells(
                                     {$h:mkE(t.CAL_IMG, {_id:"imgDateDown", _src: imagePath+"CalLeft.gif", $app_style: "; margin-left: 2px"})}
                                    ,{$h:
                                        (h.qAnc("ancMonth","")+"&nbsp;"+h.qAnc("ancYear",""))
                                       ,_style: "padding-right: 2px",_align: "center",_width:"100%"
                                    }
                                    ,{$h:mkE(t.CAL_IMG, {_id:"imgDateUp", _src: imagePath+"CalRight.gif", $app_style: "; margin-right: 4px"})}
                                    ,{$h:mkE(t.CAL_IMG, {_id:"imgSetNow", _src: imagePath+"CalButton.gif", _height: "14px", _width: "14px", $app_style: "; margin-right: 1px"})}
                                )
                +            "</tr>"
                +        "</table>"
                +    "</div>"
                +    "<div id=divCal align=center style='margin-right: "+(is.ie?-6:0)+"px;'></div>"
                +    "<div id='divTimeBlock' align='center' width='100%' style='display: none; margin: 2px 0px 0px 3px;'>"
                +        h.tblHd({_width: "100%", _border: "0"})
                +            "<tr>"+h.tblCells( {_id: "tdHour"},{$h: ":"},{_id: "tdMinute"},{$h: ":"},{_id: "tdSecond"},{ $h: h.qAnc("ancAMPM","AM",""), _style: "font-size: 70%; vertical-align: center; padding-left: 2px", _width: "100%"})+"</tr>"
                +        "</table>"
                +    "</div>"
                +"</div>"
             ;


           // Write Body
             t.ctnr.innerHTML=s;
			 oMth=getElem("ancMonth")
             aOpt=[];
             aM=["January","February","March","April","May","June","July","August","September","October","November","December"];
             for(var i=0;i<aM.length;i++)aOpt.p([aM[i],i+1]);
             qSelectWidget.create(oMth,{
                    type: qSelectWidget.TYPE_popUpSingle
                   ,rows: 12
                   ,options: aOpt
                   ,fltParent: t.ctnr
                   ,cssGen: {fontSize: "80%"}
                   ,funcValChg: function ancMonth_valChg(opt){
                   		if(opt){
                   			t.iMonth=opt.value
                   			oMth.innerHTML=opt.text
                   		} else {
                   			oMth.innerHTML="-"
                   		}
                   	}
                   ,funcGetCurVal: function ancMonth_getCurVal(){return t.iMonth}
             });
             $(oMth).bind("click", function qcal_e_ancMonth_click(e){
		        var t=_qcal,oFlt=oMth.getPopUp(),dd=oMth.getWidget();
//pc("oMth = "+qDumpObj(oMth))
		        dd.setSelected(t.iMonth-1);
		        oFlt.open({parent: oMth, position: qHtml.POS_BL, closeDelay: 2000});
		     });

           // Populate years
             oYr=getElem("ancYear");
             aOpt=[];for(var i=1970;i<2051;i++)aOpt.p([i,i]);
             qSelectWidget.create(oYr,{
                    type: qSelectWidget.TYPE_popUpSingle
                   ,rows: 12
                   ,options: aOpt
                   ,fltParent: t.ctnr, cssGen: {fontSize: "80%"}
                   ,funcValChg: function ancYear_valChg(opt){
                   		if(opt){
                   			t.iYear=opt.value
                   			oYr.innerHTML=opt.text
                   		} else {
                   			oYr.innerHTML="-"
                   		}
                   	}
                   ,funcGetCurVal: function ancYear_getCurVal(){return t.iYear}
             });
             $(oYr).bind("click", function qcal_e_ancYear_click(e){
		        var oFlt=oYr.getPopUp(),dd=oYr.getWidget();
//pc("o = "+qDumpObj(o))
		        dd.setSelectedByVal(t.iYear);
		        oFlt.open({parent: oYr, position: qHtml.POS_BL, closeDelay: 2000});
		     });
             
             

           // Populate Time
             aOpt=[["12","12", true]];
             for(var i=1;i<12;i++)aOpt.p([i,i]);
             qSW = qSelectWidget.create(getElem("tdHour"),{
                    type: qSelectWidget.TYPE_dropDown
                   ,rows: 12
                   ,options: aOpt
                   ,fltParent: t.ctnr
                   ,cssGen: {fontSize: "70%"}
             });

             qSW = qSelectWidget.create(agetElem("tdMinute"),{
                    type: qSelectWidget.TYPE_dropDown
                   ,rows: 12
                   ,options: []/* build dynamically */
                   ,fltParent: t.ctnr
                   ,cssGen: {fontSize: "70%"}
             });

			 aOpt=[];for(var i=0;i<60;i++)aOpt.p([(i>9?i:"0"+i),i]);
             qSW = qSelectWidget.create(agetElem("tdSecond"),{
                    type: qSelectWidget.TYPE_dropDown
                   ,rows: 12
                   ,options: aOpt
                   ,fltParent: t.ctnr
                   ,cssGen: {fontSize: "70%"}
             });

            t.addEvent(agetElem("imgDateDown"),"click",function qcal_e_imgDateDown_click(e){_qcal.updateCal(-1)});
            t.addEvent(agetElem("imgDateUp"),"click",function qcal_e_imgDateUp_click(e){_qcal.updateCal(1)});
            t.addEvent(agetElem("ancAMPM"),"click",t.e_ancAMPM_click);
            t.addEvent(agetElem("imgSetNow"),"click",t.e_imgSetNow_click);


        }catch(x){qErr(x)}
     }

    // HANDLERS
    ,e_ancAMPM_click: function qcal_e_ancAMPM_click(e){
        var t=_qcal, o=getEvnSource(e);
        o.innerHTML=(o.innerHTML=="AM")?"PM":"AM";
    }
    ,e_imgSetNow_click: function qcal_e_imgSetNow_click(e){
        var t=_qcal, o, d = new Date();
        t.iYear = d.getFullYear();t.iMonth = d.getMonth()+1;t.iDay = d.getDate();
        if(!isNum(t.iHour)||t.iHour==0){t.iHour=d.getHours();t.iMinute=d.getMinutes();t.iSecond=d.getSeconds();t.timeSet=false};
        t.updateCal();
    }
    ,updateCal: function Cal_updateCal(iAddMinus){
        var  t=this,iD=1,iSM,iM=t.iMonth,iY=t.iYear,iDIM
            ,sOut="",sCal="",aDB=[],iInd=0
            ,dC,dL,bEOM=false,iTR=1
            ,iWD,h=qHtml,bSecs=t.showSecs
            ,aWD=["S","M","T","W","T","F","S"]
            ,DAY=(1000*60*60*24)
        ;

        if(isNum(iAddMinus)){
            if(iAddMinus==-1){
                if(iM==1){iY--;iM=12}else{iM--};
            }else{
                if(iM==12){iY++;iM=1}else{iM++};
            };
            dC=new Date(iM+"/1/"+iY);
            t.iMonth=iM;
            t.iYear=iY;
        } else {
            dC=new Date(iM+"/1/"+iY);
        };

//pc(
//  "\n iYear    = "+t.iYear
//  +"\n iMonth  = "+t.iMonth
//  +"\n iDay    = "+t.iDay
//  +"\n iHour   = "+t.iHour
//  +"\n iMinute = "+t.iMinute
//  +"\n iSecond = "+t.iSecond
//)

        iSM=iM;
        iDIM=getDaysInMonth(iM,iY);
        iWD=dC.getDay();

        getElem("ancMonth").innerHTML=getMonthText(dC);
        getElem("ancYear").innerHTML=dC.getFullYear();

        sCal=h.tblHd({_width: "100%"})+"<tr>";for(var i=0;i<aWD.length;i++){sCal+="<td class='ctr DP_DOW' style='font-size: 75%'>"+aWD[i]+"</td>"};sCal+="</tr>";

        if(iWD>0){
            dL = new Date(dC.getTime());
            while(true){
                dL.setTime(dL.getTime()-DAY);
                d=new Date();d.setTime(dL.getTime());
                aDB.splice(0,0,d);
                if(dL.getDay()==0){break};
            };
        };

        while(true){
            if(iInd<aDB.length){// Last Month
                sCal+=ad(aDB[iInd], true);
            }else{
                iM=dC.getMonth();
//pc("2 iM = "+iM+", iSM = "+iSM+", iInd = "+iInd+", dC.getDay() = "+dC.getDay()+", dC = "+dC)
                if(iM!=iSM-1){
                    sCal+=ad(dC,true);
                    if(iInd>35 && dC.getDay()==6){
//pc("iInd = "+iInd+", dC.getDay() = "+dC.getDay())
                        sCal+="</tr>"; break;
                    };

                }else{//alert("b"+dC)
//pc("3 iM = "+iM+", dC = "+dC)
                    sCal+=ad(dC,false);
                }
                if(iD==iDIM){
                    iD=1;
                    if(iM==12){iM=1; iY++}else{iM++};
                }else{iD++};
                dC.setTime(dC.getTime()+DAY);
//pc("dC.getHours() = "+dC.getHours())
                iH=dC.getHours();
                if(iH>0){
//pc("Fixing Date (before): dC = "+dC)
                    if(iH<6)
                        dC.setTime(dC.getTime()-( (dC.getHours())*1000*60*60 ));
                    else
                        dC.setTime(dC.getTime()+( (24-dC.getHours())*1000*60*60 ));
                };
            };
            if((iInd+1)%7==0){ sCal+="</tr><tr>"; iTR++ };
            iInd++;
        };
        
        t.iMonth=iM
        t.iYear=iY

        sCal+="</table>";

        getElem("divCal").innerHTML=sCal;

        if(t.showTime && !t.timeSet){


            t.iHour=(isNum(t.iHour)?t.iHour:0);
            t.iMinute=(isNum(t.iMinute)?t.iMinute:0);
            var iHShow,bAM,iH=t.iHour;
            if(iH<11){bAM=true;}else{iH=iH-12};
            if(iH==0)iH=12;
//pc("iH = "+iH+", bAM = "+bAM)
            dd = agetElem("tdHour").getWidget();
            dd.setSelectedByVal(iH);
            dd = agetElem("tdMinute").getWidget();
            dd.setSelectedByVal(t.iMinute);
//pc("dd.getSelected() = |"+dd.getSelected()+"|")
            if(dd.getSelected().length==0)dd.setSelected(0);

            agetElem("tdSecond").style.display=(bSecs?"":"none");
            dd = agetElem("tdSecond").getWidget();
            if(dd.getSelected().length==0)dd.setSelected(0);
            
            if(bSecs){
                t.iSecond=(isNum(t.iSecond)?t.iSecond:0);
                dd = agetElem("tdSecond").getWidget();
                dd.setSelectedByVal(t.iSecond);
            };
            agetElem("ancAMPM").innerHTML=(bAM?"AM":"PM");

            t.timeSet=true;
        };

        function ad(d, bOM){
            var iM=d.getMonth(),iD=d.getDate(),iY=d.getFullYear(), iWD=d.getDay(), sM=getMonthText(iM,true)
               ,sD=(sM+" "+iD+", "+iY)
               ,sSt=(sD===t.sCurDate?"color: red; font-style: italic":sD===t.sLoadDate?"color:  purple; font-style: italic":"")
            ;
//pc(
//      "\n         sD = |"+sD+"|"
//     +"\n sLoadDate  = |"+t.sLoadDate+"|"
//     +"\n isNum(sLoadDate) = |"+isNum(t.sLoadDate)+"|"
//     +"\n sCurDate   = |"+t.sCurDate+"|"
//     +"\n (sD==sCurDate) = "+(sD===t.sCurDate)
//     +"\n (sD==sLoadDate) = "+(s$(sD)===s$(t.sLoadDate))
//     +"\n test1 =   "+(sD==="Jan 1, 2001")
//     +"\n test2 =   "+(t.sLoadDate==="Jan 1, 2001")
//     +"\n sSt = "+sSt
//)

            return (
                "<td"
                +"  class='ctr "+(iWD==0||iWD==6?"DP_WE":"DP_WD")+"'"
                +" onmouseover=\"$(this).css({borderColor:'navy', backgroundColor: '#DDDDDD'})\""
                +" onmouseout=\"$(this).css({borderColor:'#FFFFEF', backgroundColor:''})\""
                +">"
               +"<div"
               +" class="+(bOM?"OM":"TM")
               +" onclick='_qcal.selectDate("+iM+", "+iD+")'"
               +" style=\""+sSt+"; font-size: 75%\">"
                +iD
               +"</div></td>"//.format((bOM?"OM":"TM"),sM, iD, iY, sSt)
            );
        }
    }

    ,selectDate: function Cal_selectDate(iM, iD){
        var
            t=this,d,iY=t.iYear,bAM,iH,iMin,iS,sSt
           ,oDest=t.curPicker,elTB=oDest.elemVal, elTF=oDest.elemText
           ,sDtOut
        ;
        try{
            t.iMonth=iM;
            t.iDay=iD;
            sSt=(iM+1)+"/"+iD+"/"+t.iYear;
            if(t.showTime){

                iH=parseInt(agetElem("tdHour").getWidget().getSelected()[0].value);
                iMin = parseInt(agetElem("tdMinute").getWidget().getSelected()[0].value);
                iS = (t.showSecs?(parseInt(agetElem("tdSecond").getWidget().getSelected()[0].value)):0);
                bAM=(agetElem("ancAMPM").innerHTML==="AM");

//pc(
//    "\n iH = "+iH
//   +"\n iMin = "+iMin
//   +"\n iS = "+iS
//   +"\n bAM = "+bAM
//)


                if(iH===12){
                    if(bAM)(iH=0);
                }else if(!bAM)
                    iH=iH+12;

//pc(
//  "\n iH = "+iH
//   +"\n iMin = "+iMin
//   +"\n iS = "+iS
//   +"\n bAM = "+bAM
//)

                sSt+=" "+iH+":"+iMin+":"+iS;
            }

            d = new QDate(sSt);
            sDtOut=d.format(!t.showTime?t.SDF_defDate:(t.showSecs?t.SDF_defDateTimeSec:t.SDF_defDateTime));
//pc(
//    "\n Raw = "+sSt
//   +"\n sDtOut = "+sDtOut
//   +"\n t.showTime = "+t.showTime
//   +"\n t = "+t
//   +"\n oDest = "+oDest
//   +"\n d = "+d
//)


			elTB.value=sDtOut;
			if(elTF)elTF.innerHTML=sDtOut;

            t.ctnr.close();


//          _w.close()
        }catch(e){
            qErr("qCal Picker Error",e)
        }
    }
    ,toString: function(){var t=this; return "["+t.className+" ("+this.priv_no+")]"}
    ,constructor: function qDPWidget(oDiv) {this.base_constr(oDiv)}
});/*Inherit Static Members*/qObjAppend(qDPWidget,qDPWidget_StaticMembers.constants);qObjAppend(qDPWidget,qDPWidget_StaticMembers.other);
//qObjAppend(qDPWidget,__qCW_static.staticOnly,__qCW_static.constants)